/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pmbs;

import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Robert Yonas
 */
public class Frm_Monitor extends javax.swing.JFrame {

    /**
     * Creates new form Frm_Monitor
     */
    public Frm_Monitor() {
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        groupMonitor = new javax.swing.ButtonGroup();
        cbLocation = new javax.swing.JComboBox();
        lblView = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblInfo = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        listIdle = new javax.swing.JList();
        lblIdleCandidate = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        listNotification = new javax.swing.JList();
        lblNotification = new javax.swing.JLabel();

        setTitle("Information Monitor");
        setName("frmInfo");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        cbLocation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbLocationActionPerformed(evt);
            }
        });

        lblView.setText("View Location :");

        tblInfo.setAutoCreateRowSorter(true);
        tblInfo.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        tblInfo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Location", "Status", "Candidate", "Time Elapse"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInfo.setShowVerticalLines(false);
        jScrollPane1.setViewportView(tblInfo);

        listIdle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        listIdle.setModel(new DefaultListModel());
        jScrollPane2.setViewportView(listIdle);

        lblIdleCandidate.setText("Idle Candidate :");

        listNotification.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        listNotification.setForeground(new java.awt.Color(255, 51, 51));
        listNotification.setModel(new DefaultListModel());
        jScrollPane3.setViewportView(listNotification);

        lblNotification.setText("Notification");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblView)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbLocation, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
                        .addComponent(jScrollPane3))
                    .addComponent(lblIdleCandidate)
                    .addComponent(lblNotification))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblView)
                    .addComponent(cbLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIdleCandidate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblNotification)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    static InfoThread myThread;
    private void cbLocationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbLocationActionPerformed
        // change location filter
        InfoThread.room = (String) cbLocation.getSelectedItem();
    }//GEN-LAST:event_cbLocationActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // run the info thread
        myThread = new InfoThread(tblInfo, (String) cbLocation.getSelectedItem(),listNotification, listIdle, cbLocation);  
        InfoThread.isRunning = true;
        myThread.start();
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    // stop the thread if the window is closed
        //InfoThread.isRunning = false;
    }//GEN-LAST:event_formWindowClosing
    
    public static void setRunningThread(boolean val) {
        // allow other instance to stop running thread
        InfoThread.isRunning = val;        
    }
    
//    private void playSound() {
//        AudioInputStream inputStream = null;
//        try {
//            Clip clip = AudioSystem.getClip();
//            inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/pmbs/notif.wav"));
//             clip.open(inputStream);
//             clip.start();
//        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
//            Logger.getLogger(Frm_Monitor.class.getName()).log(Level.SEVERE, null, ex);
//        } 
//    }
//    
//    
//    private void playSound2() {
//        try {
//                InputStream in = Main.class.getResourceAsStream("/pmbs/notif.wav");
//                AudioStream as = new AudioStream(in);
//                
//                AudioPlayer.player.start(as); 
//
//        } catch (IOException ex) {
//            Logger.getLogger(Frm_Monitor.class.getName()).log(Level.SEVERE, null, ex);
//        }          
//    }
    
    /**
     * @param args the command line arguments
     */
    public static Frm_Monitor myMonitor;
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frm_Monitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frm_Monitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frm_Monitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frm_Monitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                if (myMonitor==null)
                    myMonitor = new Frm_Monitor();
                myMonitor.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbLocation;
    private javax.swing.ButtonGroup groupMonitor;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblIdleCandidate;
    private javax.swing.JLabel lblNotification;
    private javax.swing.JLabel lblView;
    private javax.swing.JList listIdle;
    private javax.swing.JList listNotification;
    private javax.swing.JTable tblInfo;
    // End of variables declaration//GEN-END:variables

}

class InfoThread extends Thread {
    int refreshTime;
    //public static byte sort;
    JTable table;
    public static String room;
    int notifID = 0;
    JList myList,idleList;
    JComboBox myLocation;
    public static InputStream in;
    public static boolean isRunning = true;
    public InfoThread(/*byte psort,  */JTable tbl, String location, JList list, JList idle, JComboBox cblocation) {
        super();
        refreshTime = Utility.getTimeInterval();
        //sort = psort;
        table = tbl;
        room = location;
        myList = list;
        idleList = idle;
        myLocation = cblocation;
    }
    
    @Override
    public void run() {
        while (isRunning) {
            try {
                // fill Location in combo box
                ResultSet mySet = PostGre_func.getInstance().getLocation();
                Object selected = myLocation.getSelectedItem();
                myLocation.removeAllItems();
                myLocation.addItem("[ALL]");
                try {
                    while (mySet.next()) {
                        myLocation.addItem(mySet.getString(1));
                    }
                    myLocation.setSelectedItem(selected);
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger("pmbs.CareerDay").log(java.util.logging.Level.SEVERE, null, ex);           
                }

                //load all Table Data
                mySet = PostGre_func.getInstance().showInterviewInfo(room);
                DefaultTableModel myTable = (DefaultTableModel) table.getModel();
                while(myTable.getRowCount()>0)
                    myTable.removeRow(0);
                
                try{
                    while (mySet.next()) {
                        String[] values = new String[5];
                        for (int i=1; i<5; i++) {
                            values[i-1] = mySet.getString(i);
                        }
                        if (mySet.getBoolean(3)) {
                            values[2] = "Interviewing";
                        } else {
                            values[2] = "Idle";
                        }
                        if (mySet.getTime(5)!=null) {
                            Long Elapsed = Calendar.getInstance().getTime().getTime() - mySet.getTime(5).getTime();
                            DateFormat df = new SimpleDateFormat ("mm:ss");
                            values[4] = df.format(new Date(Elapsed));
                        }
                        myTable.addRow(values);
                    }
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger("pmbs.CareerDay").log(java.util.logging.Level.SEVERE, null, ex);                    
                }
                
                //load all Notification Data
                notifID = PostGre_func.getInstance().getNotifMAX();
                ((DefaultListModel)myList.getModel()).clear();
                if (notifID>5) {
                    notifID -=5;
                } else {
                    notifID=0;
                }
                mySet = PostGre_func.getInstance().getNotifRest(notifID);
                try{
                    boolean sound = false;
                    while (mySet.next()) {
                        sound=true;
                        //((DefaultListModel)myList.getModel()).add(((DefaultListModel)myList.getModel()).getSize(),mySet.getString(1));
                        ((DefaultListModel)myList.getModel()).add(0,mySet.getString(1));
                    }
                    //if (sound) playSound();
                    
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger("pmbs.CareerDay").log(java.util.logging.Level.SEVERE, null, ex);                    
                }
                
                //load all idle candidate
                ((DefaultListModel)idleList.getModel()).clear();
                mySet = PostGre_func.getInstance().getCandidate();
                try{
                    while (mySet.next()) {
                        boolean isPresent = mySet.getBoolean(3);
                        boolean isOccupied = mySet.getBoolean(4);
                        if (isPresent && !isOccupied) {
                            ((DefaultListModel)idleList.getModel()).add(((DefaultListModel)idleList.getModel()).getSize(),mySet.getString(2));    
                        }
                    }
                
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger("pmbs.CareerDay").log(java.util.logging.Level.SEVERE, null, ex);                    
                }
                
                sleep(1000*refreshTime);
            } catch (InterruptedException ex) {
                java.util.logging.Logger.getLogger("pmbs.CareerDay").log(java.util.logging.Level.SEVERE, null, ex);
                return;
            }
        }
    }
}